package edu.tjut.tjutcommunity.controller;


import edu.tjut.tjutcommunity.entity.*;
import edu.tjut.tjutcommunity.service.CommentService;
import edu.tjut.tjutcommunity.service.PostlogsService;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yhh
 * @since 2022-04-18
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    final
    CommentService commentService;
    final
    UserService userService;

    final
    PostlogsService postlogsService;

    public CommentController(CommentService commentService, UserService userService, PostlogsService postlogsService) {
        this.commentService = commentService;
        this.userService = userService;
        this.postlogsService = postlogsService;
    }

    @PostMapping("/sendComment")
    public Message sendComment(@RequestBody Comment comment) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        if (user == null) return Message.failed("用户不存在");
        if (commentService.sendComment(comment, user, comment.getFid())) {
            postlogsService.insert(user, comment.getPid(), 1);
            return Message.ok(comment);
        }
        return Message.failed();
    }

    @PostMapping("/comment")
    public Message getComment(@RequestParam("fid") Integer fid, @RequestParam("pageNo") Integer pageNo) {
        PageResult<Comment> result = commentService.getComment(fid, pageNo);
        if (result.getResult().isEmpty()) return Message.empty();
        return Message.ok(result);
    }

    @GetMapping("/allComment/{fid}")
    public Message getComment(@PathVariable Integer fid) {
        List<Comment> result = commentService.getAllComment(fid);
        if (result.isEmpty()) return Message.empty();
        return Message.ok(result);
    }


}

